package com.gs.netty.support;

public class SynchronizedStack<T> {

    public static final int DEFAULT_SIZE = 128;
    private static final int DEFAULT_LIMIT = -1;

    // 栈的大小
    private int size;
    // 栈的大小限制
    private final int limit;

    /*
     * Points to the next available object in the stack
     */
    private int index = -1;


    private Object[] stack;


    public SynchronizedStack() {
        this(DEFAULT_SIZE, DEFAULT_LIMIT);
    }

    public SynchronizedStack(int limit) {
        this(DEFAULT_SIZE, limit);
    }

    public SynchronizedStack(int size, int limit) {
        if (limit > -1 && size > limit) {
            this.size = limit;
        } else {
            this.size = size;
        }
        this.limit = limit;
        stack = new Object[size];
    }


    public synchronized boolean push(T obj) {

        index++;

        if (index == size) {// true 证明这个栈满了，看看是否要扩容

            // limit == -1 证明是无限大
            if (limit == -1 || size < limit) {
                // 扩容
                expand();
            } else {
                // 证明不能再扩容了，这个添加的对象丢弃
                index--;
                return false;
            }
        }
        stack[index] = obj;
        return true;
    }

    @SuppressWarnings("unchecked")
    public synchronized T pop() {
        if (index == -1) {
            return null;
        }
        // 从栈去取
        T result = (T) stack[index];
        // 该位置设置为null
        stack[index--] = null;
        return result;
    }

    public synchronized void clear() {
        if (index > -1) {
            for (int i = 0; i < index + 1; i++) {
                stack[i] = null;
            }
        }
        index = -1;
    }

    private void expand() {
        // 新的的大小
        int newSize = size * 2;

        if (limit != -1 && newSize > limit) {
            // 超过最大限制就使用最大限制来充当容量大小
            newSize = limit;
        }
        // 创建新的栈
        Object[] newStack = new Object[newSize];
        System.arraycopy(stack, 0, newStack, 0, size);
        // This is the only point where garbage is created by throwing away the
        // old array. Note it is only the array, not the contents, that becomes
        // garbage.
        stack = newStack;
        size = newSize;
    }
}